package com.heima.admin.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.thread.AdThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: xrl
 * @Date: 2022/10/22  10:07
 * @Version 1.0
 */
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取登录用户的id
        String userId = request.getHeader("userId");
        //排除登录请求
        String path = request.getRequestURI().toString();
        if (path.contains("/in")) {
            return true;
        }

        //判断userId是否存在
        if (StringUtils.isBlank(userId)) {
            log.error("当前用户没有登录,请求被禁止");
            return false;
        }

        //userId不为空
        AdUser adUser = new AdUser();
        adUser.setId(Long.valueOf(userId));
        //将用户id设置到线程中
        AdThreadLocalUtil.setUser(adUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AdThreadLocalUtil.delete();
    }
}
